"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 统计信息函数
Case Name   : DBE_PERF.get_global_statio_all_sequences()描述：提供命名空间中
            所有sequences的IO状态信息，查询该函数必须具有sysadmin权限。
Create At   : 2021-05-17
Owner       : opentestcase007
Description :
    1. 创建监控权限用户
    2. 创建序列(cache 20)及关联表
    3. 系统用户非初始用户查询sequences的IO状态信息
    4. 监控管理员用户查询sequences的IO状态信息
    5. 初始用户查询sequences的IO状态信息
    6. 插入cache以内的数据，查询sequences的IO状态信息
    7. 累计插入数据50*cache，查询sequences的IO状态信息
Expect      :
    1. 创建成功
    2. 创建成功
    3. 无权限
    4. 查询成功
    5. 查询成功
    6. blks_hit值增加1，blks_read值不变
    7. blks_hit值增加大于等于50，blks_read值不变
History     :
    Modified by opentestcase024 2023/8/11:优化用例逻辑及权限校验，增加函数查询字段准确性校验
"""
import os
import unittest

from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from yat.test import Node
from yat.test import macro


class Tools(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info("----this is setup----")
        self.log.info(f"----{os.path.basename(__file__)} start----")
        self.dbuser = Node('dbuser')
        self.seq_name = 'seq_statistics_function_case0065'
        self.tb_name = 'tb_statistics_function_case0065'
        self.usr_monadmin = 'u_statistics_function_case0065'
        self.commonsh = CommonSH()
        self.constant = Constant()
        self.user_param_sys = f'-U {self.dbuser.db_user} ' \
            f'-W {self.dbuser.db_password}'
        self.user_param_mon = f'-U {self.usr_monadmin} ' \
            f'-W {macro.COMMON_PASSWD}'

    def test_built_in_func(self):
        text = '----step1：创建监控权限用户 expect：创建成功----'
        self.log.info(text)
        create_sql = f"create user {self.usr_monadmin} with monadmin " \
            f"identified by '{macro.COMMON_PASSWD}' "
        create_result = self.commonsh.execut_db_sql(create_sql)
        self.log.info(create_result)
        self.assertIn(self.constant.CREATE_ROLE_SUCCESS_MSG,
                      create_result, '执行失败:' + text)

        text = '----step2：创建序列(cache 20)及关联表 expect：创建成功----'
        self.log.info(text)
        create_sql = f"create sequence {self.seq_name} start 101 cache 20;" \
            f"create table {self.tb_name} (id int not null,name text);" \
            f"alter table {self.tb_name} alter column id set default " \
            f"nextval('{self.seq_name}');"
        create_result = self.commonsh.execut_db_sql(create_sql)
        self.log.info(create_result)
        self.assertIn(self.constant.CREATE_SEQUENCE_SUCCESS_MSG,
                      create_result, '执行失败:' + text)
        self.assertIn(self.constant.TABLE_CREATE_SUCCESS, create_result,
                      '执行失败:' + text)
        self.assertIn(self.constant.ALTER_TABLE_MSG, create_result,
                      '执行失败:' + text)

        text = '----step3：系统用户非初始用户查询sequences的IO状态信息 expect：无权限----'
        self.log.info(text)
        check_sql = f"select pg_sleep(1);select * from " \
            f"dbe_perf.get_global_statio_all_sequences() " \
            f"where relname = '{self.seq_name}';"
        check_result = self.commonsh.execut_db_sql(check_sql,
                                                   self.user_param_sys)
        self.log.info(check_result)
        self.assertIn('ERROR:  permission denied for schema dbe_perf',
                      check_result, '执行失败:' + text)

        text = '----step4：监控管理员用户查询sequences的IO状态信息 expect：查询成功----'
        self.log.info(text)
        check_result0 = self.commonsh.execut_db_sql(check_sql,
                                                    self.user_param_mon)
        self.log.info(check_result0)
        self.assertIn('1 row', check_result0, '执行失败:' + text)

        text = '----step5：初始用户查询sequences的IO状态信息 expect：查询成功----'
        self.log.info(text)
        check_result1 = self.commonsh.execut_db_sql(check_sql)
        self.log.info(check_result1)
        blks_read1 = int(check_result1.splitlines()[-2].split('|')[-2])
        blks_hit1 = int(check_result1.splitlines()[-2].split('|')[-1])
        self.assertEqual(check_result0, check_result1, '执行失败:' + text)

        text = '----step6：插入cache以内的数据，查询sequences的IO状态信息 ' \
               'expect：blks_hit值增加1，blks_read值不变----'
        self.log.info(text)
        insert_sql = f"insert into {self.tb_name}(name) values" \
            f"(generate_series(1, 19)||'name');"
        insert_result = self.commonsh.execut_db_sql(insert_sql)
        self.log.info(insert_result)
        self.assertIn(self.constant.INSERT_SUCCESS_MSG, insert_result,
                      '执行失败:' + text)
        check_result2 = self.commonsh.execut_db_sql(check_sql)
        self.log.info(check_result2)
        blks_read2 = int(check_result2.splitlines()[-2].split('|')[-2])
        blks_hit2 = int(check_result2.splitlines()[-2].split('|')[-1])
        self.assertEqual(blks_read2, blks_read1, '执行失败:' + text)
        self.assertEqual(blks_hit1 + 1, blks_hit2, '执行失败:' + text)

        text = '----step7：累计插入数据50*cache，查询sequences的IO状态信息 ' \
               'expect：blks_hit值增加大于等于50，blks_read值不变----'
        self.log.info(text)
        insert_sql = f"insert into {self.tb_name}(name) values" \
            f"(generate_series(1, 1000)||'name');"
        insert_result = self.commonsh.execut_db_sql(insert_sql)
        self.log.info(insert_result)
        self.assertIn(self.constant.INSERT_SUCCESS_MSG, insert_result,
                      '执行失败:' + text)
        check_result3 = self.commonsh.execut_db_sql(check_sql)
        self.log.info(check_result3)
        blks_read3 = int(check_result3.splitlines()[-2].split('|')[-2])
        blks_hit3 = int(check_result3.splitlines()[-2].split('|')[-1])
        self.assertEqual(blks_read3, blks_read2, '执行失败:' + text)
        self.assertGreaterEqual(blks_hit3, blks_hit2 + 50, '执行失败:' + text)

    def tearDown(self):
        self.log.info('----清理环境----')
        text1 = '----删除监控权限用户 expect：删除成功----'
        self.log.info(text1)
        drop_role_sql = f"drop user {self.usr_monadmin}"
        drop_role_result = self.commonsh.execut_db_sql(drop_role_sql)
        self.log.info(drop_role_result)
        text2 = '----删除序列及关联表 expect：删除成功----'
        self.log.info(text2)
        drop_sql = f"drop table {self.tb_name};" \
            f"drop sequence {self.seq_name};"
        drop_result = self.commonsh.execut_db_sql(drop_sql)
        self.log.info(drop_result)

        self.assertIn(self.constant.DROP_ROLE_SUCCESS_MSG,
                      drop_role_result, '执行失败:' + text1)
        self.assertIn(self.constant.DROP_SEQUENCE_SUCCESS_MSG,
                      drop_result, '执行失败:' + text2)
        self.assertIn(self.constant.TABLE_DROP_SUCCESS, drop_result,
                      '执行失败:' + text2)

        self.log.info(f"-----{os.path.basename(__file__)} end-----")
